const gradeData = () => {
	return [{
			dictCode: '1',
			dictLabel: '一年级',
			dictValue: '1'
		},
		{
			dictCode: '2',
			dictLabel: '二年级',
			dictValue: '2'
		},
		{
			dictCode: '3',
			dictLabel: '三年级',
			dictValue: '3'
		},
		{
			dictCode: '4',
			dictLabel: '四年级',
			dictValue: '4'
		},
		{
			dictCode: '5',
			dictLabel: '五年级',
			dictValue: '5'
		},
		{
			dictCode: '6',
			dictLabel: '六年级',
			dictValue: '6'
		},
		{
			dictCode: '7',
			dictLabel: '七年级',
			dictValue: '7'
		},
		{
			dictCode: '8',
			dictLabel: '八年级',
			dictValue: '8'
		},
		{
			dictCode: '9',
			dictLabel: '九年级',
			dictValue: '9'
		},
		{
			dictCode: '10',
			dictLabel: '高一',
			dictValue: '10'
		},
		{
			dictCode: '11',
			dictLabel: '高二',
			dictValue: '11'
		},
		{
			dictCode: '12',
			dictLabel: '高三',
			dictValue: '12'
		}
	]
}

const cardType = () => {
	return [{
			id: '0',
			name: '身份证'
		},
		{
			id: '1',
			name: '护照'
		}
	]
}

const genders = () => {
	return [{
			id: '0',
			name: '女'
		},
		{
			id: '1',
			name: '男'
		}
	]
}

const gradeLabel = (count) => {
	return gradeData().find(item => item.dictValue == count).dictLabel
}

const isContains = (substring) => {
	let str = "abcdefghijklmnopqrstuvwxyz";
	if (str.includes(substring)) {
		return true
	} else {
		return false
	}
}
//防止多次点击跳转的方法（函数节流）
// 使用方法
// turn : util.noDoubleClick(function (e) {
// }
const noDoubleClick = (fn, gapTime) => {
	if (gapTime == null || gapTime == undefined) {
		gapTime = 800
	}
	let _lastTime = null
	// 返回新的函数
	return function() {
		let _nowTime = +new Date()
		if (_nowTime - _lastTime > gapTime || !_lastTime) {
			fn.apply(this, arguments) //将this和参数传给原函数
			_lastTime = _nowTime
		}
	}
}

// 获取用户手机号
const getUserPhone = () => {
	let info = uni.getStorageSync('USER_INFO')
	console.log('infoinfo', info)
	if (info) {
		return JSON.parse(info).phone
	} else {
		uni.switchTab({
			url: "/pages/login/login"
		})
	}
}
const getUserID = () => {
	let info = uni.getStorageSync('USER_INFO');
	if (info) {
		return JSON.parse(info).id;
	} else {
		uni.switchTab({
			url: "/pages/login/login"
		})
	}
}
const sec_to_time = (s) => {
	var t = '';
	if (s > -1) {
		var hour = Math.floor(s / 3600);
		var min = Math.floor(s / 60) % 60;
		var sec = s % 60;
		if (hour < 10) {
			t = '0' + hour + ":";
		} else {
			t = hour + ":";
		}
		if (min < 10) {
			t += "0";
		}
		t += min + ":";
		if (sec < 10) {
			t += "0";
		}
		t += sec;
	}
	return t;
}

const deepClone = (obj) => {
	if (obj === null || typeof obj !== 'object') {
		return obj;
	}

	if (obj instanceof Date) {
		return new Date(obj.getTime());
	}

	if (obj instanceof Array) {
		return obj.reduce((arr, item, i) => {
			arr[i] = deepClone(item);
			return arr;
		}, []);
	}

	if (obj instanceof Object) {
		return Object.keys(obj).reduce((newObj, key) => {
			newObj[key] = deepClone(obj[key]);
			return newObj;
		}, {});
	}
}
const isallowInput = (Letters) => {
	var lettersArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
		's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4'
	]
	// var lettersArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
	// 	's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
	// 	'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3'
	// ]
	var isHave = lettersArray.indexOf(Letters);
	if (isHave > -1) {
		return true
	} else {
		return false
	}
}
const turnKeyCode = (keyCode) => {
	console.log('keyCode', keyCode);
	// 确保keyCode在可打印ASCII字符的范围内  
	if (keyCode > 32 && keyCode <= 126) {
		// 使用String.fromCharCode()将keyCode转换为字符  
		return String.fromCharCode(keyCode).toLowerCase();
	} else if (keyCode == 13) {
		return 'Enter'
	} else if (keyCode == 16) {
		return 'Shift'
	} else if (keyCode == 8) {
		return 'Backspace'
	} else if (keyCode == 32) {
		return 'Space'
	}
	// 如果keyCode不在可打印ASCII字符的范围内，可以返回一个空字符串或undefined  
	// 这里选择返回空字符串  
	return '';
}
const convertNumber = (num) => {
	switch (num) {
		case 1:
			return '第一题 | First Question';
		case 2:
			return '第二题 | Second Question';
		case 3:
			return '第三题 | Third Question';
		case 4:
			return '第四题 | Fourth Question';
		case 5:
			return '第五题 | Fifth Question';
		case 6:
			return '第六题 | Sixth Question';
		case 7:
			return '第七题 | Seventh Question';
		case 8:
			return '第八题 | Eighth Question';
		case 9:
			return '第九题 | Ninth Question';
		case 10:
			return '第十题 | Tenth Question';
		case 11:
			return '第十一题 | Eleventh Question';
		case 12:
			return '第十二题 | Twelfth Question';
		case 13:
			return '第十三题 | Thirteenth Question';
		case 14:
			return '第十四题 | Fourteenth Question';
		case 15:
			return '第十五题 | Fifteenth Question';
		case 16:
			return '第十六题 | Sixteenth Question';
		case 17:
			return '第十七题 | Seventeenth Question';
		case 18:
			return '第十八题 | Eighteenth Question';
		case 19:
			return '第十九题 | Nineteenth Question';
		case 20:
			return '第二十题 | Twentieth Question';
		case 21:
			return '第二十一题 | Twenty-first Question';
		case 22:
			return '第二十二题 | Twenty-second Question';
		case 23:
			return '第二十三题 | Twenty-third Question';
		case 24:
			return '第二十四题 | Twenty-fourth Question';
		case 25:
			return '第二十五题 | Twenty-fifth Question';
		case 26:
			return '第二十六题 | Twenty-sixth Question';
		case 27:
			return '第二十七题 | Twenty-seventh Question';
		case 28:
			return '第二十八题 | Twenty-eighth Question';
		case 29:
			return '第二十九题 | Twenty-ninth Question';
		case 30:
			return '第三十题 | Thirtieth Question';
		case 31:
			return '第三十一题 | Thirty-first Question';
		case 32:
			return '第三十二题 | Thirty-second Question';
		case 33:
			return '第三十三题 | Thirty-third Question';
		case 34:
			return '第三十四题 | Thirty-fourth Question';
		case 35:
			return '第三十五题 | Thirty-fifth Question';
		case 36:
			return '第三十六题 | Thirty-sixth Question';
		case 37:
			return '第三十七题 | Thirty-seventh Question';
		case 38:
			return '第三十八题 | Thirty-eighth Question';
		case 39:
			return '第三十九题 | Thirty-ninth Question';
		case 40:
			return '第四十题 | Fortieth Question';
		default:
			return "More";
	}
}
const getLastItems = (data) => {
	if (!Array.isArray(data) || data.length === 0) {
		return {
			name: '请创建您的蜂计划',
			allWordCount: 0,
			clockWordCount: 0,
			finishDays: 0,
			clockDays: 0,
			wordThesaurus: {
				name: 'please create your bee plan'
			}
		};
	}
	let lastItems = {};
	// 遍历最外层数组  
	for (let i = 0; i < data.length; i++) {
		// 假设 data 中的每个元素都是一个对象，且有一个 mouthList 属性  
		const mouthList = data[i].mouthList;
		if (Array.isArray(mouthList) && mouthList.length > 0) {
			// 遍历 mouthList 数组  
			for (let j = 0; j < mouthList.length; j++) {
				const list = mouthList[j].list;
				if (Array.isArray(list) && list.length > 0) {
					// 获取 list 数组的最新一条数据  
					lastItems = list[0];
				}
			}
		}
	}
	return lastItems;
}

const changeNumber = (num, point) => { //num是传进来的具体数字，point是我们要保留的小数点个数
	if (num == 0) {
		return 0;
	} else {
		let number = num.toString().split('.')[0] //第一步通过转换成字符串，利用.分割截取.前面的数字
		if (number.length < 6) { //对于万以下的数字我们不处理
			return number //直接返回
		} else if (number.length >= 6 && number.length <= 8) { //第二步判断！小于6直接抬走，6-8即十百千万留下
			let demical = number.substring(number.length - 4, number.length - 4 + point) //这一步呢是拿到需要的小数
			let realnumber = parseFloat(parseInt(number / 10000) + '.' + demical) +
				'万' /*这一步呢是将原本的数除于10000再将之取int拿到小数点前的数，直接加万也行，加上拿到的小数也行！*/
			return realnumber
		} else if (number.length > 8) { //这个是处理上亿的数了
			let demical = number.substring(number.length - 8, number.length - 8 + point)
			let realnumber = parseFloat(parseInt(number / 100000000) + '.' + demical) + '亿'
			return realnumber
		}
	}

}
const getBottomHeight = () => {
	let app = uni.getSystemInfoSync();
	let bottomHight = app.safeAreaInsets.bottom //屏幕底部安全距离
	console.log('屏幕底部安全距离', bottomHight) //
	return bottomHight
}



const getBackgroundMusic = (type) => {
	let myArray = [];
	if (type == 'menu') {
		myArray = [
			'/static/mp3/menu/1.mp3',
		];
	}
	if (type == 'game') {
		myArray = [
			'/static/mp3/game/1.mp3',
		];
	}
	if (type == 'rank') {
		myArray = [
			'/static/mp3/rank/1.mp3',
			// '/static/mp3/rank/2.mp3',
		];
	}
	if (type == 'finish') {
		myArray = [
			'/static/mp3/finish/finished.mp3',
		];
	}


	// 生成一个随机索引
	const randomIndex = Math.floor(Math.random() * myArray.length);

	let mp3 = '';
	// 获取随机值
	if (myArray.length > 0) {
		mp3 = myArray[randomIndex];
	} else {
		mp3 = '';
	}

	return mp3;
}

// js 从数组中随机取一个数
const getRandomFromArray = (arr) => {
	if (!Array.isArray(arr) || arr.length === 0) return undefined;
	const randomIndex = Math.floor(Math.random() * arr.length);
	return arr.splice(randomIndex, 1)[0];
}

// 判断登录
const checkLoginStatus = () => {
	let info = uni.getStorageSync('USER_INFO')
	if (!info) {
		return false;
	}
	return true;
}

// 类型标签
const typeList = () => {
	return [{
			key: 'categorize',
			value: '分类'
		},
		{
			key: 'contain',
			value: '包含'
		},
		{
			key: 'suffixes',
			value: '后缀'
		},
		{
			key: 'prefixes',
			value: '前缀'
		}
	]
}

// 一句话识别
const checkIsNeedTips = (content) => {
	content = content.toLowerCase()
	var wordTip = ["pardon", "repeat", "again", "pronunciation", "word", "world", "Water", "work", "what",
		"workplace",
		"Work", "one", "good"
	];
	var speechTip = ["part of speech", "part", "part speech", "part of", "of speech", "speech"];
	var definitionTip = ["definition", "define", "definite", "dolphin", "deafening", "defi", "defeat", " da.",
		".da"
	];
	var sentenceTip = ["sentence", "certain", "Cent", "Heaven", "Part of which"];
	var originTip = ["origin", "language", "original", "orinin", "come from", "etymology", "origan", "arigin",
		"language", 'origins'
	]; //词源

	var tipObj = {
		word: wordTip,
		part_of_speech: speechTip,
		definition: definitionTip,
		sentence: sentenceTip,
		origin: originTip,
	};

	//不需要提示
	if (!checkStringContainsAny(content, ["my word is", "the word is"])) {
		var newArr = [];
		var patterns = newArr.concat(tipObj.word, tipObj.origin, tipObj.part_of_speech, tipObj.definition, tipObj
			.sentence);

		// console.log('checkIsNeedTips-------------------', content)
		content = content.trim().toLowerCase();
		content = content.split(',').join(' ')
		content = content.split('.').join(' ')
		content = content.split('?').join(' ')
		content = " " + content + " ";
		// console.log('checkIsNeedTips-------------------', content)
		var count = 0;
		for (var i = 0; i < patterns.length; i++) {
			var item = patterns[i].trim().toLowerCase();
			if (content.includes(" " + item + " ")) {
				// console.log('item:', item)
				count++;
			}
		}
		// console.log('count-----', count)
		if (count > 0) {
			console.log("checkStringContainsAny1", true)
			return true;
		} else {
			console.log("checkStringContainsAny2", false)
			return false;
		}
	} else {
		console.log("checkStringContainsAny3", false)
		return false;
	}
}

const fnCheckResultOnlyTips = (resultText) => {
	if (resultText.trim() !== '') {
		// 判断是否需要提示
		if (
			hasStrByType(resultText, 'word')
		) {
			return 'word';
		} else if (
			hasStrByType(resultText, 'origin')
		) {
			return 'origin';
		} else if (
			hasStrByType(resultText, 'part_of_speech')
		) {
			return 'part_of_speech';
		} else if (
			hasStrByType(resultText, 'definition')
		) {
			return 'definition';
		} else if (
			hasStrByType(resultText, 'sentence')
		) {
			return 'sentence';
		} else {
			return '未匹配';
		}
	}
}

const hasStrByType = (str, type) => {
	var wordTip = ["pardon", "repeat", "again", "pronunciation", "word", "world", "Water", "work", "what",
		"workplace",
		"Work", "one", "good"
	];
	var speechTip = ["part of speech", "part", "part speech", "part of", "of speech", "speech"];
	var definitionTip = ["definition", "define", "definite", "dolphin", "deafening", "defi", "defeat", " da.",
		".da"
	];
	var sentenceTip = ["sentence", "certain", "Cent", "Heaven", "Part of which"];
	var originTip = ["origin", "language", "original", "orinin", "come from", "etymology", "origan", "arigin",
		"language", 'origins'
	]; //词源

	var tipObj = {
		word: wordTip,
		part_of_speech: speechTip,
		definition: definitionTip,
		sentence: sentenceTip,
		origin: originTip,
	};

	console.log('hasWordStr-----1991:')
	str = str.toLowerCase();
	var keywords = tipObj[type];
	// console.log('提示判断：start')
	// console.log(str, type);
	// console.log(keywords);
	// console.log('提示判断：end')
	var count = 0;
	for (let i = 0; i < keywords.length; i++) {
		var item = keywords[i];
		item = item.toLowerCase();
		if (str.includes(item)) {
			count++;
		}
	}
	if (count > 0) {
		return true;
	} else {
		return false;
	}
}

// 判断字符串包含指定的多个字符串中的某一个就行
const checkStringContainsAny = (str, substrings) => {
	// console.log("checkStringContainsAny", str, substrings)
	str = str.toLowerCase()
	return substrings.some(substring => str.includes(substring));
}

// 判断字符串包含指定的多个字符串中的某一个就行
const fnSetTimeout = (delay_time) => {
	if (!delay_time) {
		delay_time = 1000;
	}
	that
	setTimeout(function() {

	}, delay_time)
}

// reading  :your word is ...
const readingVoiceUrl = (word) => {
	return `http://spbcn.oss-cn-zhangjiakou.aliyuncs.com/jzy/word/alvoice/${word}-reading.mp3`
}
// word
const wordVoiceUrl = (word) => {
	return `http://spbcn.oss-cn-zhangjiakou.aliyuncs.com/jzy/word/alvoice/${word}.mp3`
}
const definitionVoiceUrl = (word) => {
	return `http://spbcn.oss-cn-zhangjiakou.aliyuncs.com/jzy/word/alvoice/${word}-definition.mp3`
}
const sentenceVoiceUrl = (word) => {
	return `http://spbcn.oss-cn-zhangjiakou.aliyuncs.com/jzy/word/alvoice/${word}-sentence.mp3`
}
const partOfSpeechVoiceUrl = (word) => {
	return `http://spbcn.oss-cn-zhangjiakou.aliyuncs.com/jzy/word/alvoice/${word}-partofspeech.mp3`
}
const wordErrorVoiceUrl = (word) => {
	return `http://spbcn.oss-cn-zhangjiakou.aliyuncs.com/jzy/word/alvoice/${word}-error.mp3`
}
const getNetWorkStatus = () => {
	var status = false;

	uni.getNetworkType({
		success: function(res) {
			console.log('网络状态：', res)
			if (res.networkType === 'none') {
				status = false;
				console.log('网络异常');
				// uni.showToast({
				// 	title: '网络异常',
				// 	icon: 'none'
				// })
			} else {
				status = true;
				console.log('当前网络连接正常');
				// uni.showToast({
				// 	title: '当前网络连接正常',
				// 	icon: 'none'
				// })
			}
		}
	});

	return status;
}

const getRandomInteger = (min, max) => {
	return Math.floor(Math.random() * (max - min + 1)) + min;
}

const deviceType = () => {
	return uni.getStorageSync('deviceType')
}

const getVersionNumber = (version) => {
	if (version == null || version == '') {
		console.log('版本号不存在或为0，不需要更新app');
		return 0;
	}
	var currentVersion = version;
	var currentVersionArr = currentVersion.split('.');
	var versionNumber = currentVersionArr[0] * 100 + currentVersionArr[1] * 10 + currentVersionArr[2] * 1;
	return versionNumber
}

const gameMode = () => {
	return [{
			title: '拼词竞技',
			enTitle: 'Word Competition',
			mode: 'pcjj'
		},
		{
			title: '极速拼词',
			enTitle: 'Speed Spell',
			mode: 'jspc'
		},
		{
			title: '字母接龙',
			enTitle: 'Letter By Letter',
			mode: 'zmjl'
		},
		{
			title: '词源挑战',
			enTitle: 'Origins Challenge',
			mode: 'cytz'
		},
		{
			title: '线索拼词',
			enTitle: 'Show And Spell',
			mode: 'xspc'
		},
		{
			title: '慧眼识词',
			enTitle: 'Laser Letters',
			mode: 'hysc'
		},
		{
			title: '九宫格拼词',
			enTitle: 'Super Word',
			mode: 'jggpc'
		},
		{
			title: '你问我答',
			enTitle: 'Guess and Spell',
			mode: 'nwwd'
		},
		{
			title: '神奇偏旁',
			enTitle: 'Magic Component',
			mode: 'sqpp'
		},
		{
			title: '魔力部首',
			enTitle: 'Magic Radical',
			mode: 'mlbs'
		},
		{
			title: '疯狂同音字',
			enTitle: 'Crazy Homophone',
			mode: 'fktyz'
		}
	]
}

// 网速检测
const checkInternetSpeed = (data) => {
	console.log('检测网速 checkInternetSpeed', uni.getStorageSync('internet_speed_tip_status'), uni.getStorageSync(
		'internet_speed_tip_status'))
	if (uni.getStorageSync('internet_speed_tip_status') && uni.getStorageSync(
			'internet_speed_tip_status') == 1) {
		var end_time = Date.now() / 1000; // 转换为秒
		var diff_time = parseFloat(end_time) - parseFloat(data.start_time);
		diff_time = diff_time.toFixed(3);
		console.log("diff_time===", diff_time)
		if (diff_time > uni.getStorageSync('internet_speed_tip_interval')) {
			uni.showToast({
				title: '当前网络不稳定',
				icon: 'error'
			})
		}
	}
}

// 网速检测
const getDeviceType = () => {
	var systemInfo = uni.getSystemInfoSync();
	var isTablet = systemInfo.screenWidth > 600 && systemInfo.pixelRatio < 3;
	var deviceType = "";
	if (isTablet) {
		deviceType = "pad";
		uni.setStorageSync('deviceType', deviceType);
	} else {
		deviceType = "phone";
		uni.setStorageSync('deviceType', deviceType);
	}

	// uni.showToast({
	// 	title: deviceType,
	// 	icon: 'none'
	// })

	return deviceType;
}
// 在你需要的地方调用这个函数
const getCurrentPage = () => {
	const pages = uni.getCurrentPages();
	if (pages.length > 0) {
		// 获取当前最新打开的页面
		const currentPage = pages[pages.length - 1];

		// 输出页面路径
		console.log('Current page path:', currentPage.route);

		// 返回页面实例，你可以根据需要处理
		return currentPage;
	} else {
		console.log('No pages in the stack.');
		return null;
	}
}

export default {
	gradeData,
	convertNumber,
	gradeLabel,
	noDoubleClick,
	getUserPhone,
	sec_to_time,
	cardType,
	genders,
	deepClone,
	getLastItems,
	changeNumber,
	getUserID,
	getBottomHeight,
	isContains,
	getBackgroundMusic,
	getRandomFromArray,
	isallowInput,
	turnKeyCode,
	checkLoginStatus,
	typeList,
	checkIsNeedTips,
	fnCheckResultOnlyTips,
	fnSetTimeout,
	readingVoiceUrl,
	wordVoiceUrl,
	definitionVoiceUrl,
	sentenceVoiceUrl,
	partOfSpeechVoiceUrl,
	wordErrorVoiceUrl,
	getNetWorkStatus,
	getRandomInteger,
	deviceType,
	getVersionNumber,
	gameMode,
	checkInternetSpeed,
	getDeviceType,
	getCurrentPage
}